<?php
namespace Api\Controller;
use \Common\Util\Curl;

class MemberController extends APIController
{
    protected $tbName = CONTROLLER_NAME;

    protected $tca = array(
        'user_id' => array(
            'method' => 'exists',
            'model' => 'Member',
            'code_key' => 'lawless',
        )
    );

    protected $field = ['openid','nickname','wxlogo','mobile','area','gender'];

    /**
     * 新增用户
     */
    public function addUser(){
        try{
            $this->safeChecked();
            $data = I('param.');
            //验证码
            $Base = D('Base');
            /*验证码验证*/
            $flag = $Base->vilidateCode($data['mobile'],$data['code']);
            if(!$flag){
                $this->res_data['code_key'] = 'sms_code_error';
                $this->apiReply();
            }
            //查询openid是否已存库
            $Account = M('account');
            $count = $Account->where(array('openid' => $data['openid']))->count();
            if(!$count){
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            //数据保存
            $Obj = D($this->tbName);
            $result = $Obj->where(array('openid' => $data['openid']))->find();
            if(!$result){
                $this->filterCoupon($data);
                $Obj->create($data);
                $Obj->crdate = $Obj->tstamp = time();
                $id = $Obj->add();
                $result = $Obj->find($id);
            }else{
                $this->filterCoupon($data);
                $Obj->create($data);
                $Obj->tstamp = time();
                $Obj->where(array('id' => $result['id']))->save();
                $result = $Obj->find($result['id']);
            }
            $this->res_data['data'] = $result;
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }
    /**
     * 获取openid
     * @param   string   $code 
     */
    public function getOpenid(){
        try{
            $this->safeChecked();
            $code = I('param.code');
            /*验证*/
            $data = array(
                'appid' => C('CONFIG.appid'),
                'secret' => C('CONFIG.appsecret'),
                'grant_type' => 'MD5',
                'js_code' => $code,
            );
            $Curl = new Curl('https://api.weixin.qq.com/sns/jscode2session',$data,'get','json');
            $result = $Curl->getResult();
            $result = json_decode($result,true);
            if(!$result){
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            if($result['errcode']){
                debug($result);
                $res = array('code_key' => 'fail', 'code' => 0,'data' => $result,'msg' => $result['msg']);
                $this->ajaxReturn($res);
            }else{
                //获取到openid查询是否已存库
                $Account = M('account');
                $count = $Account->where(array('openid' => $result['openid']))->count();
                if(!$count){
                    //没有则将用户openid入库
                    $id = $Account->add(array('openid' => $result['openid']));
                    if(!$id){
                        debug($Account->_sql());
                    }
                }
                $this->res_data['data'] = $result;
            }
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     *获取用户详情
     */
    public function getUserInfo(){
        
        $this->safeChecked();
        $data = I('param.');
        $userObj = D('Base');
        $table = 'member';
        $where = array('openid' => $data['openid']);
        $field = '*';
        $info = $userObj->getInfo($field,$where,$table);
        if(!$info){
            $info = null;
        }
        $this->res_data['data'] = $info;
        $this->apiReply();
    }

    /**
     * 微信授权绑定手机号
     */
    public function editPhone(){
        try{
            $this->safeChecked();
            /*消息解密*/
            $message = '';
            Vendor("Wechatdecrypt.WXBizDataCrypt");
            $pc = new \WXBizDataCrypt(C('Config.appid'), I('param.sessionKey'));
            $errCode = $pc->decryptData(I('param.encryptedData'), I('param.iv'), $message);
            if($errCode == 0){
                $data = I('param.');
                $message = json_decode($message,true);
                //查询openid是否已存库
                $Account = M('account');
                $count = $Account->where(array('openid' => $data['openid']))->count();
                if(!$count){
                    $this->res_data['code_key'] = 'fail';
                    $this->apiReply();
                }
                //数据保存
                $Obj = D($this->tbName);
                $data['mobile'] = $message['phoneNumber'];
                $result = $Obj->where(array('openid' => $data['openid']))->find();
                if(!$result){
                    $this->filterCoupon($data);
                    $Obj->create($data);
                    $Obj->crdate = $Obj->tstamp = time();
                    $id = $Obj->add();
                    $result = $Obj->find($id);
                }else{
                    $this->filterCoupon($data);
                    $Obj->create($data);
                    $Obj->tstamp = time();
                    $Obj->where(array('id' => $result['id']))->save();
                    $result = $Obj->find($result['id']);
                }
                $this->res_data['data'] = $result;
            }else{
                debug($errCode);
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /*数据筛选*/
    public function filterCoupon(&$data){
        foreach ($data as $key => $value) {
            if(!in_array($key,$this->field)){
                unset($data[$key]);
            }
        }
    }
}